# -*- coding: utf-8 -*-
import hashlib
import time
from collections import OrderedDict
import requests
import json

from django.conf import settings

from async import async_job
from common.cache import redis_cache
from common.channel.pay import check_channel_order
from common.order import db as order_db
from common.channel.db import get_channel
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import SignError, NotPayOrderError, ProcessedPayOrderError, NotResponsePayIdError
from common.utils.ip_address import check_valid_ip_address

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    'M190705112151OB': {
        'API_KEY': 'C677AB092D2B492A09594BC31234DC8E',
        'gateway': 'https://anjipay.net/pay.do',  # 请求地址
        'query_gateway': 'https://anjipay.net/query.do',  # 订单查询接口服务地址
    }
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _get_query_gateway(mch_id):
    return APP_CONF[mch_id]['query_gateway']


def _md5(parameter, key):
    m = hashlib.md5()
    m.update(parameter + key)
    return m.hexdigest().upper()


def generate_verify_sign(parameter, key):
    s = ''
    for k, v in sorted(parameter.items()):
        s += '%s=%s&' % (k, v)
    return _md5(s[:- 1], key)


def verify_notify_sign(params, key):
    params.pop('Sign_Type')
    sign = params.pop('Sign')
    calculated_sign = generate_verify_sign(params, key)
    if sign != calculated_sign:
        _LOGGER.info("anjipay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise SignError('anjipay sign not pass')


def _build_form(params, gateway):
    html = u"<head><title>loading...</title></head><form id='submit' name='submit' action='" + gateway + "' method='post'>"
    for k, v in params.items():
        html += "<input type='hidden' name='%s' value='%s'/>" % (k, v)
    html += "</form>"
    html += "<script>doc" \
            "ument.forms['submit'].submit();</script>"
    return html


# 创建支付订单
def create_charge(pay, pay_amount, info):
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    service = info.get('service')
    now_time = time.strftime('%Y%m%d%H%M%S', time.localtime())
    # 请求报文
    parameter_dict = OrderedDict((
        ('Merchant_ID', str(app_id)),
        ('Type', service),
        ('Bankcode', service),
        ('Merchant_Order', str(pay.id)),
        ('Notice_Url', '{}/pay/api/{}/anjipay/{}'.format(
            settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
        ('Amount', '%.f' % (float(pay_amount) * 100)),  # 请求的金额为分
        ('Create_Time', str(now_time)),
    ))
    parameter_dict['Sign'] = generate_verify_sign(parameter_dict, api_key)
    parameter_dict['Sign_Type'] = 'MD5'  # 不参与签名
    _LOGGER.info("anjipay create date: %s, order_id is: %s", json.dumps(parameter_dict),
                 parameter_dict['Merchant_Order'])

    html_text = _build_form(parameter_dict, _get_gateway(app_id))
    cache_id = redis_cache.save_html(pay.id, html_text)
    url = settings.PAY_CACHE_URL + cache_id
    _LOGGER.info('anjipay url: %s', url)
    return {'charge_info': url}


# OK
def check_notify_sign(request, app_id):
    _LOGGER.info("anjipay notify body: %s", request.body)
    api_key = _get_api_key(app_id)
    data = dict(request.POST.items())
    _LOGGER.info("anjipay notify data: %s, order_id is: %s", data, data['Merchant_Order'])
    verify_notify_sign(data, api_key)
    pay_id = data['Merchant_Order']
    check_valid_ip_address(str(request.META['REMOTE_ADDR']), pay_id)
    if not pay_id:
        _LOGGER.error("anjipay fatal error, out_trade_no not exists, data: %s", data)
        raise NotResponsePayIdError('anjipay event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise NotPayOrderError('anjipay pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ProcessedPayOrderError('anjipay pay %s has been processed' % pay_id)

    mch_id = pay.mch_id  # 商户编号
    trade_status = data['Status']
    trade_no = data['Merchant_Order']
    total_fee = float(data['Amount'])  # 回调金额为元
    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee,
    }

    check_channel_order(pay_id, total_fee, app_id)
    if trade_status == 'SUCCESS':
        _LOGGER.info('anjipay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    """ 查询订单 """
    pay_id = pay_order.id
    api_key = _get_api_key(app_id)
    pay = order_db.get_pay(pay_id)
    channel = get_channel(pay.channel_id)
    info = json.loads(channel.info)
    parameter_dict = OrderedDict((
        ('Merchant_ID', str(app_id)),
        ('Type', info['service']),
        ('Merchant_Order', str(pay_id)),
    ))
    parameter_dict['Sign'] = generate_verify_sign(parameter_dict, api_key)
    parameter_dict['Sign_Type'] = 'MD5'  # 不参与签名
    _LOGGER.info('anjipay query data %s, order_id is: %s', json.dumps(parameter_dict),
                 parameter_dict['Merchant_Order'])
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_get_query_gateway(app_id), data=parameter_dict, headers=headers, timeout=5)
    _LOGGER.info('anjipay query response, %s', response.text)
    data = json.loads(response.text)
    if str(data['code']) == '00':
        trade_status = data['Status']
        total_fee = float(data['Amount'])  # 查询回调金额为元
        trade_no = data['Merchant_Order']
        extend = {
            'trade_status': trade_status,
            'trade_no': trade_no,
            'total_fee': total_fee,
        }
        check_channel_order(pay_id, total_fee, app_id)
        if trade_status == 'SUCCESS':
            _LOGGER.info('anjipay query order success, mch_id:%s pay_id:%s' % (pay_order.mch_id, trade_no))
            res = order_db.add_pay_success(pay_order.mch_id, pay_order.id, total_fee, trade_no, extend)
            if res:
                async_job.notify_mch(pay_order.id)
        else:
            _LOGGER.info('anjipay query order success, but not pay success, pay pay_id: %s,trade_status:%s'
                         % (trade_no, trade_status))
    else:
        _LOGGER.warn('anjipay data error, status_code: %s, message: %s' % (data['code'], data['msg']))
